package com.nearbymap.maps;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nearbymap.model.Address;
import com.nearbymap.model.GeocodeResponse;
import com.nearbymap.model.XmlResponse;
import com.nearbymap.tooling.XmlService;

@Service
public class GeocodingService {

	@Autowired
	private XmlService xmlService;
	
	public URL getGeocodeUrl(String location, boolean isLatlng)  {

			try {
				location = URLEncoder.encode(location, "UTF-8");

				if (location == null) {
					location = "1.358798,103.963591";
					isLatlng = true;
				}
				StringBuffer urlBuffer = new StringBuffer(
						"https://maps.googleapis.com/maps/api/geocode/xml?sensor=false");
				if (isLatlng)
					urlBuffer.append("&latlng=").append(location);
				else
					urlBuffer.append("&address=").append(location);
				System.out.println("GeocdingUrl: " + urlBuffer.toString());
				return new URL(urlBuffer.toString());
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				throw new RuntimeException(e.getMessage(), e);
			} catch (MalformedURLException e) {
				e.printStackTrace();
				throw new RuntimeException(e.getMessage(), e);
			}
	}

	public Address getGeocode(String location, boolean isLatlng) {
		return new GeocodeResponse(xmlService.query(getGeocodeUrl(location, isLatlng)));
	}

	public XmlResponse query(URL xmlServiceUrl) {
		return xmlService.query(xmlServiceUrl);
	}
}
